$(function () {
    function getArticleAdd(callback) {
        //初始化图片函数
        function renderCover() {
            $('#inputCover').on('change', function () {
                const file = this.files[0]
                const src = URL.createObjectURL(file)
                $('#coverimg').prop('src', src)
            })

        }
        //初始化分类函数
        function getArticleCategory() {
            $.get('/admin/category/list', function (res) {
                let html = ` <option value="">所有分类</option>`
                res.data.forEach(item => {
                    html += `<option value="${item.id}">${item.name}</option>`
                });
                $('#category').html(html)

                callback()
            })
        }
        //初始化时间函数
        function renderLayuiDate() {
            layui.laydate.render({
                elem: '#articleDate'
            });
        }
        //初始化富文本
        function renderTimyMce() {
            tinymce.init({
                selector: "#articleContent",
                language: "zh_CN"
            })
        }

        renderCover()
        getArticleCategory()
        renderLayuiDate()
        renderTimyMce()
    }

    //获取当前的值填充到对应的框
    function articleSearch() {
        const id = uspId('id')
        // console.log(usp)
        // console.log(id)
        $.get('/admin/article/search', { id }, function (res) {
            // console.log(res)
            const data = res.data
            // console.log(data)
            $('input[name="title"]').val(data.title)
            $('#coverimg').prop('src', data.cover)
            $('#category').val(data.categoryId)
            $('input[name="date"]').val(data.date)
            $('#articleContent').val(data.content)
        })
    }

    function uspId(key) {
        const usp = new URLSearchParams(location.search)
        return usp.get(key)
    }


    getArticleAdd(articleSearch)



    //发布按钮点击事件
    $('.btn-edit').on('click', function () {
        postArticle('已发布')

    })
    //给草稿按钮添加点击事件
    $('.btn-draft').on('click', function () {
        postArticle()
    })

    function postArticle(state = '') {
        const formdata = new FormData($('form')[0])
        formdata.append('content', tinyMCE.editors['articleContent'].getContent())
        formdata.append('state', state)
        formdata.append('id', uspId('id'))
        $.ajax({
            url: '/admin/article/edit',
            type: 'post',
            data: formdata,
            contentType: false,
            processData: false,
            success(res) {
                console.log(res)
                layer.msg(res.msg);
                setTimeout(() => {
                    location.href = "article_list.html";
                }, 1500);


            }
        })


    }



})